package com.testplatfrom.project.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.testplatfrom.common.core.constant.SecurityConstants;
import com.testplatfrom.common.core.domain.R;
import com.testplatfrom.common.core.exception.project.ProjectException;
import com.testplatfrom.common.security.utils.SecurityUtils;
import com.testplatfrom.project.domain.TestplatfromProject;
import com.testplatfrom.project.domain.TestplatfromProjectmember;
import com.testplatfrom.project.domain.dto.member.*;
import com.testplatfrom.project.mapper.TestplatfromProjectMapper;
import com.testplatfrom.project.mapper.TestplatfromProjectmemberMapper;
import com.testplatfrom.project.service.TestplatfromProjectService;
import com.testplatfrom.project.service.TestplatfromProjectmemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.testplatfrom.system.api.RemoteUserService;
import com.testplatfrom.system.api.domain.SysUser;
import com.testplatfrom.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 杨森
 * @since 2023-07-13
 */
@Service
@Slf4j
public class TestplatfromProjectmemberServiceImpl extends ServiceImpl<TestplatfromProjectmemberMapper, TestplatfromProjectmember> implements TestplatfromProjectmemberService {

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private TestplatfromProjectMapper testplatfromProjectMapper;

    //添加成员
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addTestplatfromProjectMember(TestplatfromProjectmemberAdd testplatfromProjectmemberAdd) {
        TestplatfromProject testplatfromProject = testplatfromProjectMapper.selectById(testplatfromProjectmemberAdd.getTestplatfromProjectId());
        if (ObjectUtil.isNull(testplatfromProject)){
            throw new ProjectException("项目不存在");
        }
        List<Long> projectmemberAddUserIds = testplatfromProjectmemberAdd.getUserIds();
        if (ObjectUtil.isNull(projectmemberAddUserIds)&&projectmemberAddUserIds.size()==0){
            throw new ProjectException("项目新增成员id集合不能为空");
        }
        List<TestplatfromProjectmember> testplatfromProjectmembers = this.list(new LambdaQueryWrapper<TestplatfromProjectmember>().eq(TestplatfromProjectmember::getTestplatfromProjectId, testplatfromProjectmemberAdd.getTestplatfromProjectId()).in(TestplatfromProjectmember::getUserId, testplatfromProjectmemberAdd.getUserIds()));
        if (!CollectionUtils.isEmpty(testplatfromProjectmembers)){
            throw new ProjectException("请勿重复添加人员");
        }
        for (Long projectmemberAddUserId : projectmemberAddUserIds) {
            R<LoginUser> result = remoteUserService.getUserInfoByUserId(projectmemberAddUserId, SecurityConstants.INNER);
            if (result.getCode()!=200){
                log.error(result.getMsg());
                throw new ProjectException("用户id为"+projectmemberAddUserId+"调用用户服务失效");
            }
        }
        ArrayList<TestplatfromProjectmember> arrayList=new ArrayList<>();
        for (Long projectmemberAddUserId : projectmemberAddUserIds) {
            TestplatfromProjectmember projectmember = TestplatfromProjectmember.builder()
                    .testplatfromProjectId(testplatfromProjectmemberAdd.getTestplatfromProjectId())
                    .userId(projectmemberAddUserId)
                    .build();
            projectmember.setCreateBy(SecurityUtils.getUsername());
            projectmember.setCreateTime(LocalDateTime.now());
            arrayList.add(projectmember);
        }
        return saveBatch(arrayList);
    }

    //成员列表
    @Override
    public TestplatfromProjectmemberPageVo listTestplatfromProjectMember(TestplatfromProjectmemberPage testplatfromProjectmemberPage) {
        LambdaQueryWrapper<TestplatfromProjectmember> platfromProjectmemberLambdaQueryWrapper=new LambdaQueryWrapper<>();
        platfromProjectmemberLambdaQueryWrapper.like(ObjectUtil.isNotEmpty(testplatfromProjectmemberPage.getNickName()),TestplatfromProjectmember::getCreateBy,testplatfromProjectmemberPage.getNickName())
                .orderByDesc(TestplatfromProjectmember::getCreateTime);
        TestplatfromProjectmemberPage projectmemberPage = page(testplatfromProjectmemberPage, platfromProjectmemberLambdaQueryWrapper);
        //对数据进行处理
        List<TestplatfromProjectmember> projectmemberPageRecords = projectmemberPage.getRecords();
        //获取当前列表的人员ID集合 调用用户平台
        List<Long> longList = projectmemberPageRecords.stream().map(TestplatfromProjectmember::getUserId).collect(Collectors.toList());
        //返回的用户信息
        R<List<SysUser>> reponse = remoteUserService.userinfoList(longList, SecurityConstants.INNER);

        List<SysUser> reponseData = reponse.getData();
        ArrayList<TestplatfromProjectmemberVO> testplatfromProjectmemberVOS=new ArrayList<>();
        if (!ObjectUtil.isNull(reponseData)){
            Map<Long, SysUser> longSysUserMap = reponseData.stream().collect(Collectors.toMap(SysUser::getUserId, Function.identity()));
            for (TestplatfromProjectmember projectmember : projectmemberPageRecords) {
                if (ObjectUtil.isNotNull(longSysUserMap.get(projectmember.getUserId()))){
                    SysUser sysUser = longSysUserMap.get(projectmember.getUserId());
                    TestplatfromProjectmemberVO projectmemberVO = TestplatfromProjectmemberVO
                            .builder()
                            .email(sysUser.getEmail())
                            .phonenumber(sysUser.getPhonenumber())
                            .nickName(sysUser.getNickName())
                            .build();
                    BeanUtils.copyProperties(projectmember,projectmemberVO);
                    testplatfromProjectmemberVOS.add(projectmemberVO);
                }else{
                    TestplatfromProjectmemberVO projectmemberVO = TestplatfromProjectmemberVO.builder().build();
                    BeanUtils.copyProperties(projectmember,projectmemberVO);
                    testplatfromProjectmemberVOS.add(projectmemberVO);
                }
            }
        }
        return TestplatfromProjectmemberPageVo.builder()
                .current(projectmemberPage.getCurrent())
                .size(projectmemberPage.getSize())
                .records(testplatfromProjectmemberVOS)
                .total(projectmemberPage.getTotal())
                .build();
    }

    @Override
    public Boolean deleteTestplatfromProjectMember(String id) {
        return this.removeById(id);
    }

    @Override
    public R<List<SysUser>> getAllUser() {
        return remoteUserService.userinfoListall(SecurityConstants.INNER);
    }

    @Override
    public Boolean deleteTestplatfromProjectMemberUsers(TestplatfromProjectmemDeleteUser testplatfromProjectmemDeleteUser) {
        return this.removeBatchByIds(testplatfromProjectmemDeleteUser.getIds());
    }
}
